package com.jxzn.locust.config;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.jxzn.locust.dto.ResultDTO;
import com.jxzn.locust.exception.LoginExpiredException;
import com.jxzn.locust.exception.PermissionException;
import com.jxzn.locust.support.ResponseCode;


@ControllerAdvice
public class CommonExceptionHandler {
    
    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 权限错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(PermissionException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> exceptionHandler(PermissionException e) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", ResponseCode.PERMISSION);
        result.put("message", ResponseCode.PERMISSION.getMessage());
        return ResponseEntity.ok(result);
    }

    /**
     * url参数错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDTO<?> urlParametersExceptionHandle(ConstraintViolationException e) {
        return ResultDTO.param("参数错误");
    }

    @ExceptionHandler(LoginExpiredException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String loginExceptionHandle(LoginExpiredException e) {
        return "account.login";
    }

    /**
     * 未知异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultDTO<?> handle(Exception e) {
        logger.error(e.getMessage(), e);
        return ResultDTO.error();
    }
}
